<template lang="pug">
div
  div
    Button(type='primary', icon='plus', @click='modal.add = true') 新增分类
  table.table
    tbody
      tr(v-for='item in flatCategories', :key='item.id')
        td
          span(v-if='item.pid > 0') - {{ "\u0020" }}
          span {{ item.name }}
        td.text-center(width='150')
          Button(type='primary', size='small', @click='edit(item)') 编辑
          | &nbsp;&nbsp;
          Button(type='error', size='small', @click='remove(item)', :disabled='!!item.children') 删除
  Modal(
    v-model='modal.add',
    :loading='true'
    @on-ok='addCategory'
    @on-cancel='modal.add = false'
  )
    Form(v-model='formData', :label-width=60)
      FormItem(label='名称')
        Input(v-model='formData.name')
      FormItem(label='所属')
        Select(v-model='formData.pid', clearable)
          Option(:value='0') - 无 -
          Option(v-for='item in rootCategories', :value='item.id', :key='item.id') {{ item.name }}

  Modal(
    v-model='modal.edit',
    :loading='true'
    @on-ok='editCategory'
    @on-cancel='modal.edit = false'
  )
    Form(v-model='formData', :label-width=60)
      FormItem(label='名称')
        Input(v-model='formData.name')
      FormItem(label='所属')
        Select(v-model='formData.pid', clearable)
          Option(:value='0') - 无 -
          Option(v-for='item in rootCategories', :value='item.id', :key='item.id') {{ item.name }}
</template>

<script>
import cloneDeep from 'lodash.clonedeep'
import flatMap from 'lodash.flatmap'
import Api from '@/apis/category.js'

import store from '@/store'

export default {
  beforeRouteEnter (to, from, next) {
    Api.getCategories({ gid: store.state.app.id, moduleName: 'media' })
      .then(data => {
        next(vm => (vm.categories = data))
      })
  },
  data () {
    return {
      modal: {
        add: false,
        edit: false
      },
      formData: {
        id: 0,
        group_id: this.$store.state.app.id,
        name: '',
        module: 'media',
        pid: 0,
        weight: 0
      },
      categories: []
      // cols: {}
    }
  },
  computed: {
    rootCategories () {
      return this.categories.filter(item => parseInt(item.pid) === 0) || []
    },
    flatCategories () {
      return flatMap(cloneDeep(this.categories), (item) => {
        if (item.children && item.children.length > 0) {
          const children = cloneDeep(item.children)
          // delete item.children
          children.unshift(item)
          return children
        }
        return [item]
      })
    }
  },
  // mounted () {
  //   Api.getCategories({ gid: this.$store.state.app.id, moduleName: 'article' })
  //     .then(data => (this.categories = data))
  // },
  methods: {
    addCategory () {
      this.validate() && Api.postCategory(this.formData).then(cate => {
        if (parseInt(cate.pid) > 0) {
          const idx = this.categories.findIndex(item => item.id === cate.pid)
          this.categories[idx].children = this.categories[idx].children || []
          this.categories[idx].children.push(cate)
        } else {
          this.categories.push(cate)
        }
        // this.categories.push(cate)
        this.modal.add = false
        this.resetFormData()
      })
    },
    editCategory () {
      this.validate() && Api.patchCategory(this.formData).then(() => {
        this.modal.edit = false
        this.$Message.success('更新成功')
        this.resetFormData()
      })
    },
    validate () {
      if (this.formData.name.trim() === '') {
        this.$Message.alert('请填写名称')
        return false
      }

      return true
    },
    edit (item) {
      this.formData.id = item.id
      this.formData.name = item.name
      this.formData.pid = (parseInt(item.pid) && item.pid) || 0
      this.formData.weight = item.weight
      this.modal.edit = true
    },
    remove (cate) {
      this.$Modal.confirm({
        title: '即将删除以下分类',
        content: cate.name,
        loading: true,
        onOk: () => {
          Api.deleteCategory(cate.id).then(() => {
            let idx
            if (parseInt(cate.pid) > 0) {
              idx = this.categories.findIndex(item => item.id === cate.pid)
              let subIdx = this.categories[idx].children.findIndex(item => item.id === cate.id)
              this.categories[idx].children.splice(subIdx, 1)
            } else {
              idx = this.categories.findIndex(item => item.id === item.id)
              this.categories.splice(idx, 1)
            }

            this.$Modal.remove()
          })
        }
      })
    },
    resetFormData () {
      this.formData.name = ''
      this.formData.id = 0
      this.formData.pid = 0
      this.formData.weight = 0
    }
  }
}
</script>
